<?php 

class RegistrationController extends Controller
{
	public function DoControll()
	{
		$this->Title( "Sign Up" );
		
		require_once 'lib/Validation.php';
		$valid = new Validation();
		
		if( $this->view->TriedToRegister() )
		{
			if ( $valid->IsValidUsername( $this->view->GetUsername() ) ) 
			{
				if( $this->model->DoesNameExist( $this->view->GetUsername() ) )
				{
					$this->view->Error( 'Username already exists.' );
				}
			}
			else
			{
				$this->view->Error( 'Invalid username! (Valid length: 4-20) (Valid characters: A-z 0-9 _)' );
			}
			
			if ( $valid->IsValidPassword( $this->view->GetPassword() ) )
			{
				if ( !$this->model->PasswordMatch( $this->view->GetPassword(), $this->view->GetPasswordRepeat() ) )
				{
					$this->view->Error( 'Passwords do not match.' );
				}
			}
			else 
			{
				$this->view->Error( 'Invalid password! (Valid length: 6-20) (Valid characters: A-z 0-9 _)' );
			}
			
			if ( !$valid->IsValidEmail( $this->view->GetEmail() ) ) 
			{
				$this->view->Error( 'Invalid E-mail address!' );
			}

			if ( !$this->view->HasErrors() )
			{
				$this->model->RegisterUser( $this->view->GetUsername(), 
											$this->view->GetPassword(), 
											$this->view->GetEmail() );
											
				$this->view->Message( 'You are now registered! Feel free to <a href="index.php?c=login">Login</a>.' );
			}
		}
		
		$this->view->BuildRegForm();

		$this->view->PrintErrors( '<p class="error"><span>Error :(</span> _ERROR_</p>' . "\r\n" );
		$this->view->PrintMessages( '<p class="message"><span>Success \o/</span> _MESSAGE_</p>' . "\r\n" );
	}
}
